package vn.sms.lazylove;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import vn.sms.lazylove.adapter.ContactAdapter;
import vn.sms.lazylove.database.DataStore;
import vn.sms.lazylove.gui.CountSelectContactListener;
import vn.sms.lazylove.object.Contact;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ContactActivity extends Activity implements
		CountSelectContactListener {

	private ContactAdapter mContactAdapter;
	private ProgressDialog mProgressBar;
	private ListView mListView;
	private Activity mActivity;
	private Context mContext;
	private String contactJson;
	private Button btnOK, btnCancel, btnBack, btnRight;
	EditText mEdtSearch;
	private List<Contact> mObjs;
	DataStore mDatastStore;
	private int mStartMode = 1;
	private Bundle b;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_contact);
		mActivity = this;
		mContext = this;
		DataStore.init(mContext);
		mDatastStore = DataStore.getInstance();
		ContactAdapter.setCountSelectedContactListener(this);
		b = getIntent().getExtras();
		if (b != null) {
			mStartMode = b.getInt("mStartMode");
		} else {
			mStartMode = 1;
		}
		mListView = (ListView) findViewById(R.id.listview_contacts);
		LayoutInflater inflater = LayoutInflater.from(this);
		View search = inflater.inflate(R.layout.view_shared_search, null);
		mListView.addHeaderView(search, null, false);
		mEdtSearch = (EditText) findViewById(R.id.search_edt);

		TextView txt_title = (TextView) findViewById(R.id.txt_title);
		txt_title.setText(getString(R.string.txt_danh_sach_lien_he));
		btnBack = (Button) findViewById(R.id.btn_left);
		btnBack.setOnClickListener(listenerOnclickBack);
		btnRight = (Button) findViewById(R.id.btn_right);		
		btnRight.setBackgroundResource(R.drawable.selector_button_setting);
		btnOK = (Button) findViewById(R.id.btnOK);
		btnOK.setOnClickListener(listenerOnclick);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(listenerOnclickCancel);
		btnRight.setOnClickListener(onClickHelperListener);

		mEdtSearch.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// do search here
				String _keyword = mEdtSearch.getText().toString().trim()
						.toLowerCase();
				if (_keyword.equals("")) {
					if (mObjs != null) {
						mContactAdapter.setData(mObjs);
						mContactAdapter.notifyDataSetChanged();
					}
				} else {
					List<Contact> objs = new ArrayList<Contact>();
					for (Contact obj : mObjs) {
						Contact contact = (Contact) obj;
						if (contact.Name.trim().toLowerCase()
								.contains(_keyword)) {
							objs.add(obj);
						}

					}
					mContactAdapter.setData(objs);
					mContactAdapter.notifyDataSetChanged();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// do stuffs
			}

			@Override
			public void afterTextChanged(Editable s) {
				// do stuffs
			}
		});

		new ContactLoadTask().execute(0);
	}

	OnClickListener onClickHelperListener = new OnClickListener() {

		public void onClick(View v) {
			Intent myI = new Intent(mContext, CreateSmsActivity.class);
			startActivity(myI);
		}
	};

	OnClickListener listenerOnclickBack = new OnClickListener() {

		public void onClick(View arg0) {
			finish();
		}
	};

	OnClickListener listenerOnclickCancel = new OnClickListener() {

		public void onClick(View arg0) {
			finish();
		}
	};

	OnClickListener listenerOnclick = new OnClickListener() {

		public void onClick(View arg0) {
			try {

				ArrayList<Contact> mListObjectChecked = (ArrayList<Contact>) mContactAdapter
						.getSelectListContacts();
				if (!mListObjectChecked.isEmpty()) {
					Bundle bundle = new Bundle();
					bundle.putString("phone",
							mContactAdapter.getListSelectedPhone());
					if (mStartMode == 1) {
						Intent myIntent = new Intent(mContext,
								CreateSmsActivity.class);
						myIntent.putExtras(bundle);
						startActivity(myIntent);
					} else {
						Intent myIntent = new Intent();
						myIntent.putExtras(bundle);
						setResult(Activity.RESULT_OK, myIntent);
						finish();
					}
				} else {
					Toast.makeText(mContext,
							getString(R.string.txt_chon_danh_ba),
							Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				Toast.makeText(mContext, getString(R.string.txt_chon_danh_ba),
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	private List<Contact> getListContacts() {
		setContactJson("");
		JSONObject json = new JSONObject();
		JSONArray jArray = new JSONArray();
		List<Contact> contactList = new ArrayList<Contact>();
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		ContentResolver cr = getContentResolver();
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
				+ " COLLATE LOCALIZED ASC";
		Cursor cur = cr.query(uri, null, null, null, sortOrder);
		if (cur.getCount() > 0) {
			String id = "";
			String name = "";
			String phone = "";
			while (cur.moveToNext()) {
				Contact c = new Contact();
				id = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts._ID));
				name = cur
						.getString(cur
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer
						.parseInt(cur.getString(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					// get the phone number
					phone = "";
					Cursor pCur = cr.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = ?", new String[] { id }, null);
					while (pCur.moveToNext()) {
						if (!phone.equals("")) {
							phone = phone
									+ ","
									+ pCur.getString(pCur
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						} else {
							phone = pCur
									.getString(pCur
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						}
					}

					pCur.close();
				}
				c.ID = id;
				c.Name = name;
				c.Phone = phone;
				contactList.add(c);

				try {
					// create contact json object
					JSONObject js = new JSONObject();
					js.put("name", name);
					js.put("phone", phone);
					jArray.put(js);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
				}

			}
		}
		cur.close();

		try {
			json.put("data", jArray);
			setContactJson(json.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			setContactJson("");
		}

		return contactList;
	}

	@Override
	public void onResume() {
		super.onResume();
		ContactAdapter.setCountSelectedContactListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_sendsms:
			Intent myI = new Intent(mContext, SendSMSActivity.class);
			startActivity(myI);
			break;
		case R.id.menu_help:
			Intent myH = new Intent(mContext, HelperActivity.class);
			startActivity(myH);
			break;
		default:
			finish();
			break;
		}
		return true;
	}

	private void showLoadingControl() {
		mProgressBar = ProgressDialog.show(mActivity, "",
				getString(R.string.loading_default), true);

	}

	private void hideLoadingControl() {
		if (mProgressBar != null && mProgressBar.isShowing())
			mProgressBar.dismiss();

	}

	class ContactLoadTask extends AsyncTask<Integer, Integer, List<Contact>> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if (mContactAdapter == null) {
				showLoadingControl();
			}
		}

		@Override
		protected List<Contact> doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			List<Contact> objs = new ArrayList<Contact>();
			objs = getListContacts();
			return objs;
		}

		@Override
		protected void onPostExecute(List<Contact> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			hideLoadingControl();
			if (result.size() > 0) {
				mObjs = result;
				mContactAdapter = new ContactAdapter(mActivity, result);
				mListView.setAdapter(mContactAdapter);
			}
		}
	}

	public void onSelectedContactChanged(int count) {
		// TODO Auto-generated method stub
		if (btnOK != null)
			btnOK.setText(getString(R.string.txt_btnOk) + " (" + count + ")");
	}

	public String getContactJson() {
		return contactJson;
	}

	public void setContactJson(String contactJson) {
		this.contactJson = contactJson;
	}

}
